<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'

import { useLabelAddDefault, useLabelDelete, useLabelDeleteDefault, useLabelIndex, useLabelMove, useLabelSwitchShow, useLabelSwitchStatus, useSortEnableList } from '@fl/api/advertising-api/flash-management'
import type { sortIndexParam } from '@fl/api/advertising-api/model/flash-management-types'
import { SearchForm, SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { reactive } from 'vue'

import addOrEditBox from './add-label.vue'
import { useCity } from '../hooks/use-city'

const { queryCityList } = useCity()
queryCityList()
const tableRef = ref()
const lastPage = ref<number>()
const lastOne = ref<number>()

const visible = ref<boolean>(false)
const editId = ref<string>('')
const sortOptions = ref<any>()
const sortAddOptions = ref<any>()

// 搜索条件、分页参数classifyId
const initialState = {
    classifyId: '',
    cityCode: '',
}
const state = ref<sortIndexParam>(cloneDeep(initialState))
const tablePage = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const initialPage = toRaw({ ...tablePage.value })

// 查询列表
const params = computed(() => ({
    classifyId: state.value.classifyId === 'all' ? '' : state.value.classifyId,
    cityCode: state.value.cityCode ? state.value.cityCode : '',
    defaultFlag: state.value.classifyId === 'all' ? '1' : '0',
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
}))
const { data, isLoading } = useLabelIndex(params)
const records = ref()
watchEffect(() => {
    if (data.value) {
        records.value = cloneDeep(data.value?.records).reduce((pre, cur, index) => {
            cur.tempSort = index + 1
            pre.push(cur)
            return pre
        }, [])

        tablePage.value.total = data.value.total!
        lastPage.value = Math.ceil(data.value.total / tablePage.value.pageSize)
        lastOne.value = data.value.total % tablePage.value.pageSize
    }
})

// 查询列表
const { data: sortList } = useSortEnableList()
watchEffect(() => {
    if (sortList.value) {
        const sortTempOptions = cloneDeep(sortList.value).reduce((pre: any, cur: any) => {
            cur.value = cur.id
            cur.label = cur.classifyName
            pre.push(cur)
            return pre
        }, [])
        sortAddOptions.value = cloneDeep(sortTempOptions)
        sortOptions.value = cloneDeep(sortTempOptions)
        sortOptions.value.unshift({ label: '默认', value: 'all' })
    }
})

// 新增
function goToAdd() {
    visible.value = true
}

// 上移、下移
const { mutate: moveMutate } = useLabelMove()
function moveItem(row: any, type: string) {
    const params = {
        defaultFlag: state.value.classifyId === 'all' ? '1' : '0',
        id: row.id,
        type,

    }
    moveMutate(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

// 切换展示
const { mutate: switchShowMutate } = useLabelSwitchShow()
function switchShow(row: any) {
    switchShowMutate(row.id, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

// 切换状态
const { mutate: switchStatusMutate } = useLabelSwitchStatus()
function switchStatus(row: any) {
    switchStatusMutate(row.id, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

// 列表：编辑
function goToEdit(row: any) {
    visible.value = true
    editId.value = row?.id
}

// 列表：删除
const { mutate: deleteMutate } = useLabelDelete()
function deleteConfirm(row: any) {
    deleteMutate(row.id, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

// 默认展示
const { mutate: addLabelDefault } = useLabelAddDefault()
function setDefault(row: any) {
    const params = {
        defaultFlag: 1,
        lableId: row.id,
    }
    addLabelDefault(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

const { mutate: deleteLabelDefault } = useLabelDeleteDefault()
function deleteDefault(row: any) {
    const params = {
        defaultFlag: 2,
        lableId: row.id,
    }
    deleteLabelDefault(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

// 搜索
function submit(values: sortIndexParam) {
    state.value = { ...values }
    tablePage.value.currentPage = 1
}

// 重置
function reset() {
    state.value = initialState
    tablePage.value = initialPage
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

const columns: PlusColumn[] = [
    {
        label: '快讯分类',
        options: computed(() => {
            return sortOptions.value
        }),
        prop: 'classifyId',
        valueType: 'select',
    },
    /* {
        label: '所属城市',
        options: computed(() => {
            return cityOptions.value
        }),
        prop: 'cityCode',
        valueType: 'select',
    }, */
]

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 70 },
        { field: 'labelName', title: '快讯标签' },
        { field: 'cityName', title: '所属城市' },
        { field: 'orderFlag', title: '排序' },
        { field: 'classifyName', title: '关联分类' },
        { field: 'showFlag', slots: { default: 'showFlag' }, title: '展示' },
        { field: 'delFlag', slots: { default: 'delFlag' }, title: '状态' },
        { slots: { default: 'operate' }, title: '操作', width: 300 },
    ],
})
</script>

<template>
    <ElCard class="mb-20"
            shadow="never"
    >
        <SearchForm v-bind="state"
                    :columns="columns"
                    submit-text="搜索"
                    @reset="reset"
                    @submit="submit"
        />
    </ElCard>

    <ElCard shadow="never">
        <SearchTable ref="tableRef"
                     v-bind="gridOptions"
                     v-model:pager="tablePage"
                     class="table"
                     :loading="isLoading"
                     :data="records"
                     :height="626"
                     @page-change="handlePageChange"
        >
            <template #showFlag="{ row }">
                <!-- active-text="是" inactive-text="否" -->
                <el-switch v-model="row.showFlag"
                           active-value="1"
                           inactive-value="0"
                           inline-prompt
                           @change="switchShow(row)"
                />
            </template>

            <template #delFlag="{ row }">
                <!-- active-text="展示" inactive-text="隐藏" -->
                <el-switch v-model="row.delFlag"
                           active-value="1"
                           inactive-value="0"
                           inline-prompt
                           @change="switchStatus(row)"
                />
            </template>

            <template #toolbar_buttons>
                <ElButton type="primary"
                          @click="goToAdd"
                >
                    <div class="i-ic:baseline-add size-16" />
                    新增
                </ElButton>
            </template>

            <template #operate="{ row }">
                <el-button class="small"
                           text
                           :disabled="row.tempSort === 1 && tablePage.currentPage === 1"
                           @click="moveItem(row, 'up')"
                >
                    上移
                </el-button>

                <el-button class="small"
                           text
                           :disabled="tablePage.currentPage === lastPage && row.tempSort === lastOne"
                           @click="moveItem(row, 'down')"
                >
                    下移
                </el-button>

                <el-button class="small"
                           type="primary"
                           text
                           @click="goToEdit(row)"
                >
                    编辑
                </el-button>

                <el-button v-if="row.defaultFlag !== '1'"
                           class="small"
                           type="primary"
                           text
                           @click="setDefault(row)"
                >
                    设为默认
                </el-button>

                <el-button v-if="row.defaultFlag === '1'"
                           class="small"
                           type="primary"
                           text
                           @click="deleteDefault(row)"
                >
                    取消默认
                </el-button>

                <el-popconfirm title="确认删除吗？"
                               @confirm="deleteConfirm(row)"
                >
                    <template #reference>
                        <el-button class="small"
                                   text
                                   type="warning"
                        >
                            删除
                        </el-button>
                    </template>
                </el-popconfirm>
            </template>
        </SearchTable>
    </ElCard>

    <addOrEditBox v-model:visible="visible"
                  v-model:id="editId"
                  :sort-options="sortAddOptions"
    />
</template>

<style lang="scss" scoped>
:deep(.small.el-button) {
    padding: 4px;
    margin-left: 6px;
}
</style>
